<div class="tmd-doc">
<h1 class="tmd-header-1">
Code Packages and Package Imports
</h1>
<p></p>
<div class="tmd-usual">
Like many modern programming languages, Go code is also organized as code packages. To use the exported code elements (functions, types, variables and named constants, etc) in a specified package, the package must first be imported, except the <code class="tmd-code-span">builtin</code> standard code package (which is a universe package). This article will explain code packages and package imports in Go.
</div>
<p></p>
<h3 id="import" class="tmd-header-3">
Introduction of Package Import
</h3>
<p></p>
<div class="tmd-usual">
Let's view a small program which imports a standard code package. (Assume the source code of this program is stored in a file named <code class="tmd-code-span">simple-import-demo.go</code>.)
</div>
<p></p>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	fmt.Println("Go has", 25, "keywords.")
}
</code></pre>
<p></p>
<div class="tmd-usual">
Some explanations:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
The first line specifies the name of the package containing the source file <code class="tmd-code-span">simple-import-demo.go</code>. The <code class="tmd-code-span">main</code> entry function of a program must be put in a package named <code class="tmd-code-span">main</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The third line imports the <code class="tmd-code-span">fmt</code> standard package by using the <code class="tmd-code-span">import</code> keyword. The identifier <code class="tmd-code-span">fmt</code> is the package name. It is also used as the import name of, and represents, this standard package in the scope of containing source file. (Import names will be explained a below section.) There are many format functions declared in this standard package for other packages to use. The <code class="tmd-code-span">Println</code> function is one of them. It will print the string representations of an arbitrary number of arguments to the standard output.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The sixth line calls the <code class="tmd-code-span">Println</code> function. Note that the function name is prefixed with a <code class="tmd-code-span">fmt.</code> in the call, where <code class="tmd-code-span">fmt</code> is the name of the package which contains the called function. The form <code class="tmd-code-span">aImportName.AnExportedIdentifier</code> is called a <a href="https://golang.org/ref/spec#Qualified_identifiers">qualified identifier</a>. <code class="tmd-code-span">AnExportedIdentifier</code> is called an unqualified identifier.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
A <code class="tmd-code-span">fmt.Println</code> function call has no requirements for its arguments, so in this program, its three arguments will be deduced as values of their respective default types, <code class="tmd-code-span">string</code>, <code class="tmd-code-span">int</code> and <code class="tmd-code-span">string</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
For each <code class="tmd-code-span">fmt.Println</code> call, a space character is inserted between each two consecutive string representations and a newline character is printed at the end.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
Running this program, you will get the following output:
</div>
<pre class="tmd-code output">
$ go run simple-import-demo.go
Go has 25 keywords.
</pre>
<p></p>
<div class="tmd-usual">
Please note, only exported code elements in a package can be used in the source file which imports the package. An exported code element uses an <a href="keywords-and-identifiers.html#identifier">exported identifier</a> as its name. For example, the first character of the identifier <code class="tmd-code-span">Println</code> is an upper case letter (so the <code class="tmd-code-span">Println</code> function is exported), which is why the <code class="tmd-code-span">Println</code> function declared in the <code class="tmd-code-span">fmt</code> standard package can be used in the above example program.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
The built-in functions, <code class="tmd-code-span">print</code> and <code class="tmd-code-span">println</code>, have similar functionalities as the corresponding functions in the <code class="tmd-code-span">fmt</code> standard package. Built-in functions can be used without importing any packages.
</div>
<p></p>
<div class="tmd-usual">
Note, the two built-in functions, <code class="tmd-code-span">print</code> and <code class="tmd-code-span">println</code>, are not recommended to be used in the production environment, for they are not guaranteed to stay in the future Go versions.
</div>
<p></p>
<div class="tmd-usual">
All standard packages are listed <a href="https://golang.org/pkg/">here</a> (the official one) or <a href="https://docs.go101.org/std/index.html">here</a> (an unofficial one, maintained by Go 101). We can also <a href="go-toolchain.html#doc">run a local server</a> to view Go documentation.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
A package import is also called an import declaration formally in Go. An import declaration is only visible to the source file which contains the import declaration. It is not visible to other source files in the same package.
</div>
<p></p>
<div class="tmd-usual">
Let's view another example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"
import "math/rand"

func main() {
	fmt.Printf("Next pseudo-random number is %v.\n", rand.Uint32())
}
</code></pre>
<p></p>
<div class="tmd-usual">
This example imports one more standard package, the <code class="tmd-code-span">math/rand</code> package, which is a sub-package of the <code class="tmd-code-span">math</code> standard package. This package provides some functions to produce pseudo-random numbers.
</div>
<p></p>
<div class="tmd-usual">
Some explanations:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
In this example, the package name <code class="tmd-code-span">rand</code> is used as the import name of the imported <code class="tmd-code-span">math/rand</code> standard package. A <code class="tmd-code-span">rand.Uint32()</code> call will return a random <code class="tmd-code-span">uint32</code> integer number.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">Printf</code> is another commonly used function in the <code class="tmd-code-span">fmt</code> standard package. A call to the <code class="tmd-code-span">Printf</code> function must take at least one argument. The first argument of a <code class="tmd-code-span">Printf</code> function call must be a <code class="tmd-code-span">string</code> value, which specifies the format of the printed result. The <code class="tmd-code-span">%v</code> in the first argument is called a format verb, it will be replaced with the string representation of the second argument. As we have learned in the article <a href="basic-types-and-value-literals.html">basic types and their literals</a>, the <code class="tmd-code-span">\n</code> in a double-quoted string literal will be escaped as a newline character.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
The above program will always output:
</div>
<pre class="tmd-code output">
Next pseudo-random number is 2596996162.
</pre>
<p></p>
<div class="tmd-usual">
Note: before Go 1.20, if we expect the above program to produce a different random number at each run, we should set a different seed by calling the <code class="tmd-code-span">rand.Seed</code> function when the program just starts.
</div>
<p></p>
<div class="tmd-usual">
If multiple packages are imported into a source file, we can group them in one import declaration by enclosing them in a <code class="tmd-code-span">()</code>.
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

// Multiple packages can be imported together.
import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	// Set the random seed (only needed before Go 1.20).
	rand.Seed(time.Now().UnixNano())
	fmt.Printf("Next pseudo-random number is %v.\n", rand.Uint32())
}
</code></pre>
<p></p>
<div class="tmd-usual">
Some explanations:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
this example imports one more package, the <code class="tmd-code-span">time</code> standard package, which provides many time related utilities.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
function <code class="tmd-code-span">time.Now()</code> returns the current time, as a value of type <code class="tmd-code-span">time.Time</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">UnixNano</code> is a method of the <code class="tmd-code-span">time.Time</code> type. The method call <code class="tmd-code-span">aTime.UnixNano()</code> returns the number of nanoseconds elapsed since January 1, 1970 UTC to the time denoted by <code class="tmd-code-span">aTime</code>. The return result is a value of type <code class="tmd-code-span">int64</code>, which is also the parameter type of the <code class="tmd-code-span">rand.Seed</code> function (note: the <code class="tmd-code-span">rand.Seed</code> function has been deprecated since Go 1.20). Methods are special functions. We can learn methods in the article <a href="method.html">methods in Go</a> for details later.
</div>
</li>
</ul>
<p></p>
<p></p>
<h3 class="tmd-header-3">
More About <code class="tmd-code-span">fmt.Printf</code> Format Verbs
</h3>
<p></p>
<div class="tmd-usual">
As mentioned above, if there is one format verb in the first argument of a <code class="tmd-code-span">fmt.Printf</code> call, it will be replaced with the string representation of the second argument. In fact, there can be multiple format verbs in the first <code class="tmd-code-span">string</code> argument. The second format verb will be replaced with the string representation of the third argument, and so on.
</div>
<p></p>
<div class="tmd-usual">
In Go 101, only the following listed format verbs will be used.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">%v</code>, which will be replaced with the general string representation of the corresponding argument.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">%T</code>, which will be replaced with the type name or type literal of the corresponding argument.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">%x</code>, which will be replaced with the hex string representation of the corresponding argument. Note, the hex string representations for values of some kinds of types are not defined. Generally, the corresponding arguments of <code class="tmd-code-span">%x</code> should be strings, integers, integer arrays or integer slices (arrays and slices will be explained in a later article).
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">%s</code>, which will be replaced with the string representation of the corresponding argument. The corresponding argument should be a string or byte slice.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Format verb <code class="tmd-code-span">//</code> represents a percent sign.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
An example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	a, b := 123, "Go"
	fmt.Printf("a == %v == 0x%x, b == %s\n", a, a, b)
	fmt.Printf("type of a: %T, type of b: %T\n", a, b)
	fmt.Printf("1// 50// 99//\n")
}
</code></pre>
<p></p>
<div class="tmd-usual">
Output:
</div>
<pre class="tmd-code output">
a == 123 == 0x7b, b == Go
type of a: int, type of b: string
1% 50% 99%
</pre>
<p></p>
<div class="tmd-usual">
For more <code class="tmd-code-span">Printf</code> format verbs, please read the online <a href="https://golang.org/pkg/fmt/"><code class="tmd-code-span">fmt</code> package documentation</a>, or view the same documentation by running a local documentation server. We can also run <code class="tmd-code-span">go doc fmt</code> to view the documentation of the <code class="tmd-code-span">fmt</code> standard package, and run <code class="tmd-code-span">go doc fmt.Printf</code> to view the documentation of the <code class="tmd-code-span">fmt.Printf</code> function, in a terminal.
</div>
<p></p>
<p></p>
<h3 id="package" class="tmd-header-3">
Package Folder, Package Import Path and Package Dependencies
</h3>
<p></p>
<div class="tmd-usual">
A code package may consist of several source files. These source files are located in the same folder. The source files in a folder (not including subfolders) must belong to the same package. So, a folder corresponds to a code package, and vice versa. The folder containing the source files of a code package is called the folder of the package.
</div>
<p></p>
<div class="tmd-usual">
For Go Toolchain, a package whose import path containing an <code class="tmd-code-span">internal</code> folder name is viewed as a special package. It can only be imported by the packages in and under the direct parent directory of the <code class="tmd-code-span">internal</code> folder. For example, package <code class="tmd-code-span">.../a/b/c/internal/d/e/f</code> and <code class="tmd-code-span">.../a/b/c/internal</code> can only be imported by the packages whose import paths have a <code class="tmd-code-span">.../a/b/c</code> prefix.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
When one source file in a package imports another package, we say the importing package depends on the imported package.
</div>
<p></p>
<div class="tmd-usual">
Go doesn't support circular package dependencies. If package <code class="tmd-code-span">a</code> depends on package <code class="tmd-code-span">b</code> and package <code class="tmd-code-span">b</code> depends on package <code class="tmd-code-span">c</code>, then source files in package <code class="tmd-code-span">c</code> can't import package <code class="tmd-code-span">a</code> and <code class="tmd-code-span">b</code>, and source files in package <code class="tmd-code-span">b</code> can't import package <code class="tmd-code-span">a</code>.
</div>
<p></p>
<div class="tmd-usual">
Surely, source files in a package can't, and don't need to, import the package itself.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Later, we will call the packages named with <code class="tmd-code-span">main</code> and containing <code class="tmd-code-span">main</code> entry functions as <span class="tmd-bold">program packages</span> (or <span class="tmd-bold">command packages</span>), and call other packages as <span class="tmd-bold">library packages</span>. Program packages are not importable. Each Go program should contain one and only one program package.
</div>
<p></p>
<div class="tmd-usual">
The name of the folder of a package is not required to be the same as the package name. However, for a library package, it will make package users confused if the name of the package is different from the name of the folder of the package. The cause of the confusion is that the default import path of a package is the name of the package but what is contained in the import path of the package is the folder name of the package. So please try to make the two names identical for each library package.
</div>
<p></p>
<div class="tmd-usual">
On the other hand, it is recommended to give each program package folder a meaningful name other than its package name, <code class="tmd-code-span">main</code>.
</div>
<p></p>
<h3 id="init" class="tmd-header-3">
The <code class="tmd-code-span">init</code> Functions
</h3>
<p></p>
<div class="tmd-usual">
There can be multiple functions named as <code class="tmd-code-span">init</code> declared in a package, even in a source code file. The functions named as <code class="tmd-code-span">init</code> must neither have any input parameters nor return results.
</div>
<p></p>
<div class="tmd-usual">
Note, at the top package-level block, the <code class="tmd-code-span">init</code> identifier can only be used in function declarations. We can't declare package-level variable/constants/types which names are <code class="tmd-code-span">init</code>.
</div>
<p></p>
<div class="tmd-usual">
At run time, each <code class="tmd-code-span">init</code> function will be (sequentially) invoked once and only once (before invoking the <code class="tmd-code-span">main</code> entry function). So the meaning of the <code class="tmd-code-span">init</code> functions are much like the static initializer blocks in Java.
</div>
<p></p>
<div class="tmd-usual">
Here is a simple example which contains two <code class="tmd-code-span">init</code> functions:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func init() {
	fmt.Println("hi,", bob)
}

func main() {
	fmt.Println("bye")
}

func init() {
	fmt.Println("hello,", smith)
}

func titledName(who string) string {
	return "Mr. " + who
}

var bob, smith = titledName("Bob"), titledName("Smith")
</code></pre>
<p></p>
<div class="tmd-usual">
The output of this program:
</div>
<pre class="tmd-code output">
hi, Mr. Bob
hello, Mr. Smith
bye
</pre>
<p></p>
<h3 id="initialization-order" class="tmd-header-3">
Resource Initialization Order
</h3>
<p></p>
<div class="tmd-usual">
At run time, a package will be loaded after all its dependency packages. Each package will be loaded once and only once.
</div>
<p></p>
<div class="tmd-usual">
All <code class="tmd-code-span">init</code> functions in all involved packages in a program will be invoked sequentially. An <code class="tmd-code-span">init</code> function in an importing package will be invoked after all the <code class="tmd-code-span">init</code> functions declared in the dependency packages of the importing package for sure. All <code class="tmd-code-span">init</code> functions will be invoked before invoking the <code class="tmd-code-span">main</code> entry function.
</div>
<p></p>
<div class="tmd-usual">
The invocation order of the <code class="tmd-code-span">init</code> functions in the same source file is from top to bottom. Go specification recommends, but doesn't require, to invoke the <code class="tmd-code-span">init</code> functions in different source files of the same package by the alphabetical order of filenames of their containing source files. So it is not a good idea to have dependency relations between two <code class="tmd-code-span">init</code> functions in two different source files.
</div>
<p></p>
<div class="tmd-usual">
All package-level variables declared in a package are initialized before any <code class="tmd-code-span">init</code> function declared in the same package is invoked.
</div>
<p></p>
<div class="tmd-usual">
Go runtime will try to initialize package-level variables in a package by their declaration order, but a package-level variable will be initialized after all of its depended variables for sure. For example, in the following code snippet, the initializations the four package-level variables happen in the order <code class="tmd-code-span">y</code>, <code class="tmd-code-span">z</code>, <code class="tmd-code-span">x</code>, and <code class="tmd-code-span">w</code>.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">func f() int {
	return z + y
}

func g() int {
	return y/2
}

var (
	w       = x
	x, y, z = f(), 123, g()
)
</code></pre>
<p></p>
<div class="tmd-usual">
About more detailed rule of the initialization order of package-level variables, please read the article <a href="evaluation-orders.html#package-level-variables">expression evaluation order</a>.
</div>
<p></p>
<p></p>
<h3 class="tmd-header-3">
Full Package Import Forms
</h3>
<p></p>
<div class="tmd-usual">
In fact, the full form of an import declaration is
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">import importname "path/to/package"
</code></pre>
<p></p>
<div class="tmd-usual">
where <code class="tmd-code-span">importname</code> is optional, its default value is the name (not the folder name) of the imported package.
</div>
<p></p>
<div class="tmd-usual">
In fact, in the above used import declarations, the <code class="tmd-code-span">importname</code> portions are all omitted, for they are identical to the respective package names. These import declarations are equivalent to the following ones:
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">import fmt "fmt"        // &lt;=&gt; import "fmt"
import rand "math/rand" // &lt;=&gt; import "math/rand"
import time "time"      // &lt;=&gt; import "time"
</code></pre>
<p></p>
<div class="tmd-usual">
If the <code class="tmd-code-span">importname</code> portion presents in an import declaration, then the prefix tokens used in qualified identifiers must be <code class="tmd-code-span">importname</code> instead of the name of the imported package.
</div>
<p></p>
<div class="tmd-usual">
The full import declaration form is not used widely. However, sometimes we must use it. For example, if a source file imports two packages with the same name, to avoid making compiler confused, we must use the full import form to set a custom <code class="tmd-code-span">importname</code> for at least one package in the two.
</div>
<p></p>
<div class="tmd-usual">
Here is an example of using full import declaration forms.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import (
	format "fmt"
	random "math/rand"
	"time"
)

func main() {
	random.Seed(time.Now().UnixNano())
	format.Print("A random number: ", random.Uint32(), "\n")

	// The following line fails to compile,
	// for "rand" is not identified.
	/*
	fmt.Print("A random number: ", rand.Uint32(), "\n")
	*/
}
</code></pre>
<p></p>
<div class="tmd-usual">
Some explanations:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
we must use <code class="tmd-code-span">format</code> and <code class="tmd-code-span">random</code> as the prefix token in qualified identifiers, instead of the real package names <code class="tmd-code-span">fmt</code> and <code class="tmd-code-span">rand</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">Print</code> is another function in the <code class="tmd-code-span">fmt</code> standard package. Like <code class="tmd-code-span">Println</code> function calls, a <code class="tmd-code-span">Print</code> function call can take an arbitrary number of arguments. It will print the string representations of the passed arguments, one by one. If two consecutive arguments are both not string values, then a space character will be automatically inserted between them in the print result.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
The <code class="tmd-code-span">importname</code> in the full form import declaration can be a dot (<code class="tmd-code-span">.</code>). Such imports are called dot imports. To use the exported elements in the packages being dot imported, the prefix part in qualified identifiers must be omitted.
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import (
	. "fmt"
	. "time"
)

func main() {
	Println("Current time:", Now())
}
</code></pre>
<p></p>
<div class="tmd-usual">
In the above example, <code class="tmd-code-span">Println</code> instead of <code class="tmd-code-span">fmt.Println</code>, and <code class="tmd-code-span">Now</code> instead of <code class="tmd-code-span">time.Now</code> must be used.
</div>
<p></p>
<div class="tmd-usual">
Generally, dot imports reduce code readability, so they are not recommended to be used in formal projects.
</div>
<p></p>
<div class="tmd-usual">
The <code class="tmd-code-span">importname</code> in the full form import declaration can be the blank identifier (<code class="tmd-code-span">_</code>). Such imports are called anonymous imports (some articles elsewhere also call them blank imports). The importing source files can't use the exported code elements in anonymously imported packages. The purpose of anonymous imports is to initialize the imported packages (each of <code class="tmd-code-span">init</code> functions in the anonymously imported packages will be called once).
</div>
<p></p>
<div class="tmd-usual">
In the following example, all <code class="tmd-code-span">init</code> functions declared in <a href="https://golang.org/pkg/net/http/pprof/">the <code class="tmd-code-span">net/http/pprof</code> standard package</a> will be called before the <code class="tmd-code-span">main</code> entry function is called.
</div>
<p></p>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import _ "net/http/pprof"

func main() {
	... // do some things
}
</code></pre>
<p></p>
<h3 class="tmd-header-3">
Each Non-Anonymous Import Must Be Used at Least Once
</h3>
<p></p>
<div class="tmd-usual">
Except anonymous imports, other imports must be used at least once. For example, the following example fails to compile.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import (
	"net/http" // error: imported and not used
	. "time"   // error: imported and not used
)

import (
	format "fmt"  // okay: it is used once below
	_ "math/rand" // okay: it is not required to be used
)

func main() {
	format.Println() // use the imported "fmt" package
}
</code></pre>
<p></p>
<p></p>
<h3 class="tmd-header-3">
Modules
</h3>
<p></p>
<div class="tmd-usual">
A module is a collection of several packages. After being downloaded to local, these packages are all contained in the same folder, which is called the root folder of the module. A module may has many versions, which follow <a href="https://semver.org/">Semantic Versioning</a> specification. About more modules related concepts and how to manage and use modules, please read the <a href="https://golang.org/ref/mod">official documentation</a>.
</div>
<p></p>
<p></p>
</div>
